package com.sand.service.Imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sand.dao.IBaseDao;
import com.sand.entity.ContractEntity;
import com.sand.entity.ContractperformEntity;
import com.sand.entity.HouseEntity;
import com.sand.service.IContractService;
import com.sand.util.PageModel;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service(value = "contractService")
public class ContractServiceImp implements IContractService {
/**
 *
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/12/6/006 21:51
 */
    //Dao层接口
    @Resource(name = "baseDao")
    private IBaseDao baseDao;

    //根据id查询合同
    @Override
    public HashMap<String, Object> queryContractById(int id) {
        List<HashMap<String, Object>> list = baseDao.queryObject(" select new Map(" +
                "t0.rid as rid,t0.status as contractStatus,t0.contractDate as contractDate,t0.content as content," +
                "t0.confirm as confirm ,t1.rid as orderId,t2.userId as landId,t2.rid as houseId," +
                "t1.leaseEffectiveTime as leaseEffectiveTime,t1.leaseExpirationTime as leaseExpirationTime," +
                "t1.totalRentalPrice as totalRentalPrice,t1.status as status," +
                "t1.remark as remark,t3.communityName as communityName,t3.communityAddress as communityAddress,t4.name as userName,t5.phone as userPhone) " +
                "from ContractEntity t0 inner join OrdertableEntity t1 on t0.orderId=t1.rid " +
                "inner join HouseEntity t2 on t1.houseId=t2.rid " +
                "inner join CommunityEntity t3 on t2.communityId=t3.rid " +
                "inner join UserdetailsEntity t4 on t1.userId=t4.userId " +
                "inner join UserinfoEntity t5 on t4.userId=t5.rid " +
                "where t0.rid=?0", id);
        HashMap<String, Object> map = list.get(0);
        List<HashMap<String,Object>> list1 = baseDao.queryObject("select new Map(t1.name as name,t2.phone as phone) " +
                "from UserdetailsEntity t1,UserinfoEntity t2 where t1.userId=t2.rid " +
                "and t1.userId=?0", Integer.parseInt(map.get("landId").toString()));
        map.put("name",list1.get(0).get("name"));
        map.put("phone",list1.get(0).get("phone"));

        return map;
    }
    //根据id查询账单
    @Override
    public HashMap<String, Object> queryBillById(int id) {
        HashMap<String, Object> map = new HashMap<>();
        List<HashMap<String, Object>> list = baseDao.queryObject(" select new Map(" +
                "t1.rid as rid,t1.status as status,t1.contractDate as contractDate,t1.confirm as confirm) " +
                "from ContractEntity t1 where t1.rid=?0", id);
        map.put("obj",list.get(0));
        List<ContractperformEntity> list2 = baseDao.queryObject("from ContractperformEntity t1 where t1.contractId=?0", id);
        map.put("list",list2);
        return map;
    }
    //根据id查询执行合同
    @Override
    public ContractperformEntity queryBillByPlayId(int rid) {
        List<ContractperformEntity> list = baseDao.queryObject("from ContractperformEntity t1 where t1.rid=?0", rid);
        return list.get(0);
    }

    //分页查询合同
    @Override
    public PageModel<HashMap<String, Object>> queryContractLimit(int limit, int page, String condition) {
        PageModel<HashMap<String, Object>> pm = new PageModel<HashMap<String, Object>>();
        //计算开始位置
        int begin=(page-1)*limit;
        //创建查询对象
        DetachedCriteria dc = DetachedCriteria.forClass(ContractEntity.class);
        //添加模糊查询条件
        if(condition!=null){
            JSONObject obj = JSON.parseObject(condition);

            if(obj.get("confirm")!=null && !"".equals(obj.get("confirm"))){
                dc.add(Restrictions.eq("confirm",obj.get("confirm").toString()));
            }
            //-1:等待确认，0:履行中，1：租客停止合同，2：房东停止合同
            if(obj.get("status")!=null && !"".equals(obj.get("status"))){
                dc.add(Restrictions.in("status",Integer.parseInt(obj.get("status").toString())));
            }
        }
        List<Long> list1 = baseDao.queryObjectCommon(dc.setProjection(Projections.rowCount()));
        dc.setProjection(null);
        dc.setProjection(Projections.property("rid"));
        dc.addOrder(Order.desc("rid"));
        List list = baseDao.queryObjectLimit(dc, begin, limit);
        long i=list1.get(0);
        int count= (int) i;

        List<HashMap<String, Object>> list2 = baseDao.queryObject(" select new Map(" +
                "t1.rid as rid,t1.status as status,t1.contractDate as contractDate,t1.confirm as confirm," +
                "t2.leaseEffectiveTime as leaseEffectiveTime,t2.leaseExpirationTime as leaseExpirationTime)" +
                "from ContractEntity t1 inner join OrdertableEntity t2 on t1.orderId=t2.rid " +
                "where t1.rid in (?0)", list);

        pm.setList(list2);
        pm.setPageNo(page);
        pm.setPageSize(limit);
        pm.setPagecount(count);
        return pm;
    }

    /**
     * 根据房东Id查询合同
     * @param limit
     * @param page
     * @param condition
     * @return
     */
    @Override
    public PageModel<HashMap<String, Object>> queryContractByUseridLimit(int limit, int page,String condition) {

        PageModel<HashMap<String, Object>> map = new PageModel<>();
        //分页开始的位置
        page = (page-1)*limit;
        //创建查询对象
        DetachedCriteria criteria = DetachedCriteria.forClass(ContractEntity.class);
        //添加模糊查询条件
        if(condition!=null){
            JSONObject obj = JSON.parseObject(condition);
            if(obj.get("userId")!=null && !"".equals(obj.get("userId"))){
                List list=baseDao.queryObject("select t1.rid  from ContractEntity t1 " +
                        "inner join OrdertableEntity t2 on t1.orderId=t2.rid " +
                        "inner join HouseEntity t3 on t3.rid=t2.houseId " +
                        "where t3.userId = ?0",Integer.parseInt(obj.get("userId").toString()));
                criteria.add(Restrictions.in("rid",list));
            }
        }
        List<Long> list1 = baseDao.queryObjectCommon(criteria.setProjection(Projections.rowCount()));

        criteria.setProjection(null);
        criteria.setProjection(Projections.property("rid"));
        criteria.addOrder(Order.desc("rid"));
        List list = baseDao.queryObjectLimit(criteria, page, limit);
        long i=list1.get(0);
        int count= (int) i;
        List<HashMap<String, Object>> list2 = baseDao.queryObject("select new Map(t1.status as status,t1.contractDate as contractDate," +
                "t1.confirm as confirm,t1.rid as rid,t2.leaseEffectiveTime as leaseEffectiveTime,t2.leaseExpirationTime as leaseExpirationTime)" +
                "from ContractEntity t1 inner join OrdertableEntity t2 on t1.orderId=t2.rid " +
                "inner join HouseEntity t3 on t3.rid=t2.houseId " +
                "where t1.rid in (?0)", list);
        map.setList(list2);
        map.setPageNo(page);
        map.setPageSize(limit);
        map.setPagecount(count);
        return map;
    }
    //查看合同信息
    @Override
    public ContractEntity queryContractByLand(int rid) {

//        List<HashMap<String,Object>> list1 = baseDao.queryObject("select new Map(t1.rid as rid,t1.leaseEffectiveTime as leaseEffectiveTime," +
//                "t1.leaseExpirationTime as leaseExpirationTime,t1.totalRentalPrice as totalRentalPrice," +
//                "t2.rid as houseId,t2.price as price,t2.paymentMethod as paymentMethod,t2.houseType as houseType," +
//                "t3.housePicture as housePicture,t4.name as userName) " +
//                "from OrderServiceImp t1 inner join HouseServiceImp t2 on t1.houseId=t2.rid " +
//                "inner join HouseattachmentEntity t3 on t2.rid=t3.houseId " +
//                "inner join UserdetailsEntity t4 on t1.userId=t4.userId " +
//                "where t3.isHouse=0 and t1.rid=?0 group by t2.rid", rid);
//        HashMap<String, Object> map = list1.get(0);

//        List<HashMap<String,Object>> list = baseDao.queryObject("select new Map(t1.rid as rid,t1.contractDate as contractDate,t1.content as content," +
//                "t2.leaseEffectiveTime as leaseEffectiveTime,t2.leaseExpirationTime as leaseExpirationTime," +
//                "t3.phone as userPhone,t4.name as userName,t4.idCard as userIdCard,t5.rid as houseId,t5.userId as landId," +
//                "t5.constructionArea as constructionArea,t5.paymentMethod as paymentMethod,t5.price as price," +
//                "t6.communityName as communityName,t6.communityAddress as communityAddress,t7.name as cityName," +
//                "t8.rentPaymentDate as rentPaymentDate) " +
//                "from ContractEntity t1 inner join ContractperformEntity t8 on t8.contractId=t1.rid " +
//                "inner join OrdertableEntity t2 on t1.orderId=t2.rid " +
//                "inner join UserinfoEntity t3 on t2.userId=t3.rid " +
//                "inner join UserdetailsEntity t4 on t3.rid=t4.userId " +
//                "inner join HouseEntity t5 on t2.houseId=t5.rid " +
//                "inner join CommunityEntity t6 on t5.communityId=t6.rid " +
//                "inner join CityEntity t7 on t6.cityId=t7.rid " +
//                "where t1.rid=?0", rid);
//        HashMap<String, Object> map = list.get(0);
//        //查询房东信息
//        List<HashMap<String,Object>> list1 = baseDao.queryObject("select new Map(" +
//                "t1.phone as phone,t2.name as name,t2.idCard as idCard) " +
//                "from UserinfoEntity t1 inner join UserdetailsEntity t2 on t1.rid=t2.userId " +
//                "where t1.rid=?0", Integer.parseInt(map.get("landId").toString()));
//        HashMap<String, Object> map1 = list1.get(0);
//        map.put("landPhone",map1.get("phone"));
//        map.put("landName",map1.get("name"));
//        map.put("landIdCard",map1.get("idCard"));
//        //计算日期
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        try {
//            String begin = map.get("leaseEffectiveTime").toString();
//            String end = map.get("leaseExpirationTime").toString();
//            map.put("leaseEffectiveTime",sdf.format(map.get("leaseEffectiveTime")));
//            map.put("leaseExpirationTime",sdf.format(map.get("leaseExpirationTime")));
//            map.put("contractDate",sdf.format(map.get("contractDate")));
//            String day=sdf.format(map.get("rentPaymentDate"));
//            map.put("rentPaymentDate",day.substring(day.lastIndexOf("-")+1,day.length()));
//
//            Date d1=sdf.parse(begin);
//            Date d2=sdf.parse(end);
//            long con=(d2.getTime()-d1.getTime())/(60*60*24*1000)/30;
//            map.put("mouth",con);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//
//        String str="出租人（甲方):"+map.get("userName")+"\t承租人（乙方）及单位:"+map.get("landName")+"\n" +
//                "电话:"+map.get("userPhone")+"\t\t电话:"+map.get("landPhone")+"\n" +
//                "身份证号:"+map.get("userIdCard")+"\t\t身份证号:"+map.get("landIdCard")+"\n" +
//                "甲、乙、三方根据中华人民共和国有关法律﹑行政法规和苏州市相关地方性法规的规定，在合法、平等、自愿相互信任的基础上签订本合同，承诺共同遵守。\n" +
//                "1.甲方将其位于__"+map.get("cityName")+map.get("communityName")+map.get("communityAddress")+"__的房屋（以下简称“该房屋”)租给乙方使用，房屋面积为__"+map.get("constructionArea")+"__平方米。\n" +
//                "2.该房屋租赁期限共_"+map.get("mouth")+"_个月，自_"+map.get("leaseEffectiveTime")+"_至_"+map.get("leaseExpirationTime")+"_止。\n" +
//                "3.该房屋租金为人民币_"+map.get("price")+"_元整/月（此价格不含相关税费）﹐乙方应同时交纳首期租金_"+Integer.parseInt(map.get("price").toString())*(Integer.parseInt(map.get("paymentMethod").toString())+1)+"_元给甲方。\n" +
//                "4.该房屋租金按_"+map.get("paymentMethod")+"_支付，支付时间为 每月_"+map.get("rentPaymentDate")+"_号，以甲方实际收到为准。\n" +
//                "\n" +
//                "签订日期：_"+map.get("contractDate")+"_\n";
//        map.put("str",str);
//        System.out.println("=============>>>>"+str);

        List<ContractEntity> list = baseDao.queryObject("from ContractEntity t1 where t1.rid=?0", rid);
        return list.get(0);
    }

    /**
     * 查询租客合同记录
     * @param limit
     * @param page
     * @param condition
     * @return
     */
    @Override
    public PageModel<HashMap<String, Object>> queryTenantContractViewLimit(int limit, int page, String condition) {
        PageModel<HashMap<String, Object>> map = new PageModel<>();
        //分页开始的位置
        page = (page-1)*limit;
        //创建查询对象
        DetachedCriteria criteria = DetachedCriteria.forClass(ContractEntity.class);
        //添加模糊查询条件
        if(condition!=null){
            JSONObject obj = JSON.parseObject(condition);
            if(obj.get("userId")!=null && !"".equals(obj.get("userId"))){
                List list=baseDao.queryObject("select t1.rid  from ContractEntity t1 " +
                        "inner join OrdertableEntity t2 on t1.orderId=t2.rid " +
                        "where t2.userId = ?0",Integer.parseInt(obj.get("userId").toString()));
                criteria.add(Restrictions.in("rid",list));
            }
            if (obj.get("confirm")!=null && !"".equals(obj.get("confirm"))) {
                criteria.add(Restrictions.eq("confirm", obj.get("confirm")));
            }
        }
        List<Long> list1 = baseDao.queryObjectCommon(criteria.setProjection(Projections.rowCount()));

        criteria.setProjection(null);
        criteria.setProjection(Projections.property("rid"));
        criteria.addOrder(Order.desc("rid"));
        List list = baseDao.queryObjectLimit(criteria, page, limit);
        long i=list1.get(0);
        int count= (int) i;
        List<HashMap<String, Object>> list2 = baseDao.queryObject("select new Map(" +
                "t1.rid as rid,t1.contractDate as contractDate,t1.status as status," +
                "t5.name as name)" +
                "from ContractEntity t1 " +
                "inner join OrdertableEntity t2 on t2.rid=t1.orderId " +
                "inner join HouseEntity t3 on t3.rid=t2.houseId " +
                "inner join ContractperformEntity t4 on t4.contractId=t1.rid  " +
                "inner join UserdetailsEntity t5 on t5.userId=t2.userId " +
                "where t1.rid in (?0) group by t1.rid", list);
        map.setList(list2);
        map.setPageNo(page);
        map.setPageSize(limit);
        map.setPagecount(count);
        return map;
    }
    //根据用户查询账单
    @Override
    public List<ContractperformEntity> queryBillByUser(int rid,int isAll) {
        if(isAll==1){
            List<ContractperformEntity> list = baseDao.queryObject("select t1 from ContractperformEntity t1 inner join ContractEntity t2 on t1.contractId=t2.rid " +
                    "inner join OrdertableEntity t3 on t2.orderId=t3.rid where t3.userId=?0", rid);
            return list;
        }else{
            List<ContractperformEntity> list = baseDao.queryObject("select t1 from ContractperformEntity t1 inner join ContractEntity t2 on t1.contractId=t2.rid " +
                    "inner join OrdertableEntity t3 on t2.orderId=t3.rid where t1.status=0 and t3.userId=?0", rid);
            return list;
        }
    }

    @Override
    public boolean addContract(String data) {
        return false;
    }

    @Override
    public boolean updateContract(String data) {

        return false;
    }

    @Override
    public boolean delContract(String data) {
        return false;
    }
    //修改合同审核状态
    @Override
    public boolean updateContractStatus(int id,int status) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<ContractEntity> list = baseDao.queryObject("from ContractEntity t1 where t1.rid=?0", id);
        ContractEntity contract = list.get(0);
        //判断合同是否已在执行,只有未确认的合同可以审核
        if(contract.getStatus()!=-1){
            return false;
        }

        switch (status){
            case 0:
                contract.setConfirm("审核未通过");
                break;
            case 1:
                contract.setConfirm("审核通过");
                contract.setStatus(0);
                break;
        }
        boolean bln = baseDao.updateObject(contract);
        if(bln){
            List<HashMap<String,Object>> list1 = baseDao.queryObject("select new Map(" +
                    "t2.leaseEffectiveTime as leaseEffectiveTime,t2.leaseExpirationTime as leaseExpirationTime," +
                    "t2.totalRentalPrice as totalRentalPrice,t3.paymentMethod as paymentMethod,t3.price as price) " +
                    "from ContractEntity t1 inner join OrdertableEntity t2 on t1.orderId=t2.rid " +
                    "inner join HouseEntity t3 on t2.houseId=t3.rid " +
                    "where t1.rid=?0", contract.getRid());
            HashMap<String, Object> map = list1.get(0);

            String begin = map.get("leaseEffectiveTime").toString();
            String end = map.get("leaseExpirationTime").toString();
            int price = Integer.parseInt(map.get("price").toString());
            int paymentMethod = Integer.parseInt(map.get("paymentMethod").toString());

            try {
                //计算租赁月数
                Date d1=sdf.parse(begin);
                Date d2=sdf.parse(end);
                long con=(d2.getTime()-d1.getTime())/(60*60*24*1000)/30;
                int conn=(int)con;
                System.out.println(con);
                if(paymentMethod==0){
                    for (int i = 1; i <= conn; i++) {
                        ContractperformEntity conty = new ContractperformEntity();

                        conty.setAmount((long)price);
                        conty.setContractId(id);
                        conty.setPhase(i);
                        conty.setStatus(0);
                        //下次缴费时间
                        String str = sdf.format(d1);
                        String[] split = str.split("-");
                        if("29".equals(split[2]) || "30".equals(split[2]) || "31".equals(split[2])){
                            str=split[0]+"-"+split[1]+"-28";
                        }
                        str=split[0]+"-"+(Integer.parseInt(split[1])+i-1)+"-"+split[2];

                        conty.setRentPaymentDate(new Timestamp(sdf.parse(str).getTime()));
                        baseDao.addObject(conty);
                    }
                }else{
                    for (int i = 1; i <= (conn%paymentMethod==0?conn/paymentMethod:conn/paymentMethod+1); i++) {
                        ContractperformEntity conty = new ContractperformEntity();
                        //首页金额加1
                        if(i==1){
                            conty.setAmount((long)price*(paymentMethod+1));
                        }else if(i==conn/paymentMethod+1){
                            conty.setAmount((long)price*(conn%paymentMethod));
                        }else{
                            conty.setAmount((long)price*paymentMethod);
                        }
                        conty.setContractId(id);
                        conty.setPhase(i);
                        conty.setStatus(0);

                        //下次缴费时间
                        String str = sdf.format(d1);
                        String[] split = str.split("-");
                        if("29".equals(split[2]) || "30".equals(split[2]) || "31".equals(split[2])){
                            str=split[0]+"-"+split[1]+"-28";
                        }
                        str=split[0]+"-"+(Integer.parseInt(split[1])+(i-1)*paymentMethod)+"-"+split[2];

                        conty.setRentPaymentDate(new Timestamp(sdf.parse(str).getTime()));
                        baseDao.addObject(conty);
                    }
                }
                return true;
            } catch (ParseException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    //支付租金
    @Override
    public boolean updateBillStatus(int rid,String payMethod) {
        //创建时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        List<ContractperformEntity> list = baseDao.queryObject("from ContractperformEntity t1 where t1.rid=?0", rid);
        ContractperformEntity con = list.get(0);
        con.setStatus(1);
        con.setPayTime(timestamp);
        con.setPayMethod(payMethod);
        boolean bln = baseDao.updateObject(con);
        if(bln)return true;
        return false;
    }
}
